package com.sutong.platform.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sutong.common.result.BaseResponse;
import com.sutong.common.result.ErrorCode;
import com.sutong.platform.annotation.AuthCheck;
import com.sutong.platform.common.DeleteRequest;
import com.sutong.platform.common.IdRequest;
import com.sutong.platform.common.ResultUtils;
import com.sutong.platform.constant.UserConstant;
import com.sutong.platform.exception.BusinessException;
import com.sutong.platform.exception.ThrowUtils;
import com.sutong.platform.model.dto.interfaceinfo.*;
import com.sutong.platform.model.entity.InterfaceInfo;
import com.sutong.platform.model.entity.User;
import com.sutong.platform.model.enums.InterfaceInfoStatusEnum;
import com.sutong.platform.model.vo.InterfaceInfoDetail;
import com.sutong.platform.model.vo.InterfaceInfoVo;
import com.sutong.platform.model.vo.InterfaceMethodAnalysisVo;
import com.sutong.platform.model.vo.InterfaceTotalVo;
import com.sutong.platform.service.InterfaceInfoService;
import com.sutong.platform.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 接口信息的接口
 *
 * @author sutong
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody @Validated InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = BeanUtil.copyProperties(interfaceInfoAddRequest, InterfaceInfo.class);
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        interfaceInfo.setStatus(1);
        boolean result = interfaceInfoService.save(interfaceInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(interfaceInfo.getId());
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody @Validated DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param interfaceInfoUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody @Validated InterfaceInfoUpdateRequest interfaceInfoUpdateRequest) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = BeanUtil.copyProperties(interfaceInfoUpdateRequest, InterfaceInfo.class);
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfo> getInterfaceInfoById(Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(@RequestBody InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size),
                interfaceInfoService.getQueryWrapper(interfaceInfoQueryRequest));
        return ResultUtils.success(interfaceInfoPage);
    }

    // endregion


    /**
     * 发布
     *
     * @param idRequest
     * @return
     */
    @PostMapping("/online")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody @Validated IdRequest idRequest) {
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(idRequest.getId());
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // TODO 判断接口是否可以调用

        // 修改接口的状态
        boolean result = interfaceInfoService.lambdaUpdate()
                .set(InterfaceInfo::getStatus, InterfaceInfoStatusEnum.ONLINE.getValue())
                .eq(InterfaceInfo::getId, idRequest.getId())
                .update();
        return ResultUtils.success(result);
    }

    /**
     * 下线
     *
     * @param idRequest
     * @return
     */
    @PostMapping("/offline")
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody @Validated IdRequest idRequest) {
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(idRequest.getId());
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 修改接口的状态
        boolean result = interfaceInfoService.lambdaUpdate()
                .set(InterfaceInfo::getStatus, InterfaceInfoStatusEnum.OFFLINE.getValue())
                .eq(InterfaceInfo::getId, idRequest.getId())
                .update();
        return ResultUtils.success(result);
    }

    /**
     * 查询所有
     *
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfoVo>> listInterfaceIdAndName(String name) {
        List<InterfaceInfo> list = interfaceInfoService
                .lambdaQuery()
                .select(InterfaceInfo::getId, InterfaceInfo::getName)
                .like(StrUtil.isNotBlank(name), InterfaceInfo::getName, name)
                .list();
        List<InterfaceInfoVo> result = list.stream().map(interfaceInfo ->
                BeanUtil.copyProperties(interfaceInfo, InterfaceInfoVo.class)
        ).collect(Collectors.toList());
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取详情
     *
     * @param id
     * @return
     */
    @GetMapping("/get/detail")
    public BaseResponse<InterfaceInfoDetail> getInterfaceInfoDetailById(Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfoDetail interfaceInfo = interfaceInfoService.getDetailById(id);
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 在线调用
     *
     * @param callRequest
     * @return
     */
    @PostMapping("/call")
    public BaseResponse<InterfaceInfoCallResponse> interfaceInfoCall(@RequestBody @Validated InterfaceInfoCallRequest callRequest,
                                                                     HttpServletRequest request) {
        // 获取当前用户
        User loginUser = userService.getLoginUser(request);
        InterfaceInfoCallResponse response = interfaceInfoService.interfaceInfoCall(callRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 查看接口请求方式占比
     */
    @GetMapping("/analysis")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<InterfaceMethodAnalysisVo>> listInterfaceMethodCond() {
        List<InterfaceMethodAnalysisVo> result = interfaceInfoService.methodAnalysis();
        return ResultUtils.success(result);
    }

    /**
     * 首页展示接口统计信息
     */
    @GetMapping("/total")
    public BaseResponse<InterfaceTotalVo> getInterfaceTotalCond() {
        InterfaceTotalVo result = interfaceInfoService.totalAnalysis();
        return ResultUtils.success(result);
    }

}
